﻿using System;
using System.Linq;
using API.IRepositories;
using API.EntityModels;
using API.Helpers;


namespace API.Repositories
{
    public class DrinkOrderRepository : IDrinkOrderRepository
    {
        public void Delete(int id)
        {
            var entity = Save(Get(id).FirstOrDefault(), typeof(DrinkOrder));
        }

        public IQueryable<DrinkOrder> Get(int drinkOrderId)
        {
            var entities = ConnectionHelper.GetEntityConnection();
            return from d in entities.DrinkOrders
                   where d.DrinkOrderId == drinkOrderId
                   select d;
        }

        public EntityModels.DrinkOrder Save(DrinkOrder entity, Type baseEmptyEntityOnType)
        {
            using (var entityConnection = ConnectionHelper.GetEntityConnection())
            {
                if (entity.DrinkOrderId > 0)
                {
                    var emptyEntity = EntityFrameworkHelper.BuildEmptyEntityForAttachment(entity, baseEmptyEntityOnType);
                    emptyEntity.DrinkOrderId = entity.DrinkOrderId;
                    entityConnection.DrinkOrders.Attach(emptyEntity);
                    entityConnection.DrinkOrders.ApplyCurrentValues(entity);
                }
                else
                {
                    entity = EntityFrameworkHelper.ResetEntityForAdd(entity, baseEmptyEntityOnType);
                    entity.Created = DateTime.Now;
                    entityConnection.DrinkOrders.AddObject(entity);
                }

                entityConnection.SaveChanges();
                return Get().FirstOrDefault(d => d.DrinkOrderId == entity.DrinkOrderId);
            }
        }


        public IQueryable<DrinkOrder> Get()
        {
            return ConnectionHelper.GetEntityConnection().DrinkOrders.AsQueryable();
        }
    }
}




